import 'dart:convert';
import 'dart:io';

import 'package:explore/act/main.dart';
import 'package:explore/delact/main.dart';
import 'package:explore/delmember/main.dart';
import 'package:explore/errorSign/main.dart';
import 'package:explore/joinAliance/main.dart';
import 'package:fluent_ui/fluent_ui.dart' as fluent;
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../login/main.dart';
import '../provider/person_info.dart';
import 'dart:math';
import 'package:open_file_plus/open_file_plus.dart';
import 'package:path_provider/path_provider.dart';

import '../register/main.dart';

class Tool extends StatefulWidget {
  const Tool({super.key});

  @override
  State<StatefulWidget> createState() => _Tool();
}

class _Tool extends State<Tool> {
  @override
  Widget build(BuildContext context) {
    return Consumer<PersonInfo>(builder: (ctx, person, child) {
      return Expanded(
          child: Container(
              padding: const EdgeInsets.all(10),
              margin: const EdgeInsets.only(top: 20, bottom: 20),
              height: 150,
              width: double.infinity,
              decoration: BoxDecoration(
                border: Border.all(
                  color: const Color.fromARGB(255, 107, 102, 102),
                  width: 2,
                ),
              ),
              child: Wrap(
                  alignment: WrapAlignment.start,
                  spacing: 35.0,
                  children: [
                        const Setaction(title: "修改资料", image: "rename.png"),
                        const Setaction(title: "请假申请", image: "leave.png"),
                      ] +
                      (person.status == "管理"
                          ? [
                              const Setaction(title: "设置行动", image: "act.png"),
                              const Setaction(
                                  title: "删除行动", image: "deleteAct.png"),
                              const Setaction(
                                  title: "战报打印", image: "print.png"),
                              const Setaction(
                                  title: "行动补签", image: "errorSign.png"),
                              const Setaction(title: "成员加入", image: "join.png"),
                              const Setaction(
                                  title: "删除成员", image: "deleteMember.png"),
                            ]
                          : []) +
                      [const Setaction(title: "退出登录", image: "exit.png")])));
    });
  }
}

class Setaction extends StatefulWidget {
  final String title;
  final String image;
  const Setaction({super.key, required this.title, required this.image});
  @override
  State<StatefulWidget> createState() => _Setaction();
}

class _Setaction extends State<Setaction> {
  var color = Colors.black;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    final personInfo = Provider.of<PersonInfo>(context, listen: false);
    String url = widget.image.split(".")[0];
    if (personInfo.examine) {
      if (url == "join") {
        setState(() {
          color = Colors.red;
        });
      }
    }
  }

  void execlprint(PersonInfo person) async {
    final url = Uri.parse('http://127.0.0.1:5000/print');
    final headers = {'Content-Type': 'application/json;charset=utf-8'};
    final body = jsonEncode({
      'alliance': person.alliance,
    });
    final response = await http.post(url, headers: headers, body: body);
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path;
    var random = Random();

    var num = random.nextInt(10100);
    File file = File('$appDocPath/generated_excel-$num.xlsx');
    await file.writeAsBytes(response.bodyBytes);
    await OpenFile.open('$appDocPath/generated_excel-$num.xlsx');
  }

  void rename(BuildContext context, PersonInfo person) async {
    var name = "";
    var password = "";

    await showDialog<String>(
      context: context,
      builder: (context) => fluent.ContentDialog(
        title: const Text('修改资料'),
        content: Container(
            height: 150,
            margin: const EdgeInsets.only(left: 18, right: 18),
            child: Column(
              children: [
                fluent.InfoLabel(
                  label: '名字',
                  child: fluent.TextBox(
                    placeholder: '名字',
                    expands: false,
                    controller: TextEditingController(text: person.name),
                    style:
                        const TextStyle(textBaseline: TextBaseline.alphabetic),
                    onChanged: (value) {
                      name = value;
                    },
                  ),
                ),
                const SizedBox(
                  height: 20,
                ),
                fluent.InfoLabel(
                  label: '密码',
                  child: fluent.TextBox(
                    placeholder: '密码',
                    expands: false,
                    controller: TextEditingController(text: person.password),
                    style:
                        const TextStyle(textBaseline: TextBaseline.alphabetic),
                    onChanged: (value) {
                      password = value;
                    },
                  ),
                ),
              ],
            )),
        actions: [
          fluent.Button(
            child: const Text('取消'),
            onPressed: () {
              Navigator.pop(context, '取消');
              // Delete file here
            },
          ),
          fluent.Button(
            child: const Text('确认'),
            onPressed: () async {
              final url = Uri.parse('http://127.0.0.1:5000/rename');
              final headers = {
                'Content-Type': 'application/json;charset=utf-8'
              };
              final body = jsonEncode({
                'name': person.name,
                'new_name': name == "" ? person.name : name,
                'new_password': password == "" ? person.password : password,
                'alliance': person.alliance
              });
              var response = await http.post(url, headers: headers, body: body);
              if (response.statusCode == 200) {
                Fluttertoast.showToast(msg: '修改成功');
              } else {
                Fluttertoast.showToast(msg: '修改失败');
              }
              // ignore: use_build_context_synchronously
              Navigator.pop(context, '确认');
              person.changName(value: name == "" ? person.name : name);
            },
          ),
        ],
      ),
    );
    setState(() {});
  }

  void leave(BuildContext context, PersonInfo person) async {
    await showDialog<String>(
        context: context,
        builder: (context) => Container(
              margin: const EdgeInsets.only(left: 18, right: 18),
              child: fluent.ContentDialog(
                title: const Text('申请请假'),
                content: const Text(
                  '此次行动是否需要请假',
                ),
                actions: [
                  fluent.Button(
                    child: const Text('取消'),
                    onPressed: () async {
                      Navigator.pop(context, '取消');
                      // Delete file here
                    },
                  ),
                  FilledButton(
                    child: const Text('确认'),
                    onPressed: () async {
                      final url = Uri.parse('http://127.0.0.1:5000/leave');
                      final headers = {
                        'Content-Type': 'application/json;charset=utf-8'
                      };
                      final body = jsonEncode({
                        'name': person.name,
                        'act': person.act,
                        'alliance': person.alliance,
                      });
                      final response =
                          await http.post(url, headers: headers, body: body);
                      if (response.statusCode == 200) {
                        Fluttertoast.showToast(msg: '请假成功');
                      } else {
                        Fluttertoast.showToast(msg: '请假失败');
                      }
                      Navigator.pop(context, '确认');
                    },
                  ),
                ],
              ),
            ));
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<PersonInfo>(builder: (ctx, person, child) {
      return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () async {
            String url = widget.image.split(".")[0];
            if (url == "act") {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (BuildContext context) => const Act()));
            }
            if (url == "print") {
              execlprint(person);
            }
            if (url == "rename") {
              rename(context, person);
            }
            if (url == "leave") {
              leave(context, person);
            }
            if (url == "errorSign") {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (BuildContext context) => const Errorsign()));
            }
            if (url == "deleteAct") {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (BuildContext context) => const DelAct()));
            }
            if (url == "deleteMember") {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (BuildContext context) => const DelMember()));
            }
            if (url == "join") {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (BuildContext context) => const JoinAliance()));
            }
            if (url == "exit") {
              final SharedPreferences prefs =
                  await SharedPreferences.getInstance();
              prefs.remove("account");
              prefs.remove("password");
              Navigator.of(context)
                  .pushNamedAndRemoveUntil('/', ModalRoute.withName('/'));
            }
          },
          onLongPress: () async {
            String imageName = widget.image.split(".")[0];
            final personInfo = Provider.of<PersonInfo>(context, listen: false);
            final url = Uri.parse('http://127.0.0.1:5000/change_examine');
            final headers = {'Content-Type': 'application/json;charset=utf-8'};
            if (imageName == "join") {
              if (color == Colors.red) {
                final body = jsonEncode(
                    {'alliance': person.alliance, 'examine': !person.examine});
                var response =
                    await http.post(url, headers: headers, body: body);
                if (response.statusCode == 200) {
                  setState(() {
                    color = Colors.black;
                  });
                  personInfo.changExamine(value: false);
                } else {
                  Fluttertoast.showToast(msg: '修改失败');
                }
              } else {
                final body = jsonEncode(
                    {'alliance': person.alliance, 'examine': !person.examine});
                var response =
                    await http.post(url, headers: headers, body: body);
                if (response.statusCode == 200) {
                  setState(() {
                    color = Colors.red;
                  });
                  personInfo.changExamine(value: true);
                } else {
                  Fluttertoast.showToast(msg: '修改失败');
                }
              }
            }
          },
          child: Container(
              margin: EdgeInsets.only(
                  top: MediaQuery.of(context).size.width * 0.05),
              child: Column(children: [
                ColorFiltered(
                  colorFilter: ColorFilter.mode(color, BlendMode.srcIn),
                  child: Image.asset(
                    "image/${widget.image}",
                    width: MediaQuery.of(context).size.width * 0.05,
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
                Text(
                  widget.title,
                  style: TextStyle(
                      fontSize: MediaQuery.of(context).size.width * 0.03),
                )
              ])));
    });
  }
}
